package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class OracleJdbcTest {

  //数据库连接对象
  private static Connection conn = null;

  private static String driver = "oracle.jdbc.driver.OracleDriver"; //驱动

  // private static String url = "jdbc:oracle:thin:@//192.168.11.228:1521/orcl"; //连接字符串
  private static String url = "jdbc:oracle:thin:@//192.168.11.160:1521/orcl"; //连接字符串

  private static String username = "sys as sysdba"; //用户名

  private static String password = "1"; //密码


  // 获得连接对象
  private static synchronized Connection getConn() {
    if (conn == null) {
      try {
        Class.forName(driver);

        Properties props = new Properties();
        props.put("oracle.net.encryption_client", "accepted");
        props.put("oracle.net.encryption_types_client", "RC4_256");
        props.put("oracle.net.crypto_checksum_client", "REQUIRED");                //此行根据官方文档写，未作验证
        props.put("oracle.net.crypto_checksum_types_client", "MD5");             //此行根据官方文档格式写，未作验证
        props.put("user", "sys as sysdba");
        props.put("password", "1");
        conn = DriverManager.getConnection(url, props);
        //conn = DriverManager.getConnection(url, username, password);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    return conn;
  }

  //执行查询语句
  public void query(String sql, boolean isSelect) throws SQLException {
    PreparedStatement pstmt;

    try {
      pstmt = getConn().prepareStatement(sql);
      //建立一个结果集，用来保存查询出来的结果
      ResultSet rs = pstmt.executeQuery();
      while (rs.next()) {
        String name = rs.getString(1);
        System.out.println(name);
      }
      rs.close();
      pstmt.close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  public void query(String sql) throws SQLException {
    PreparedStatement pstmt;
    pstmt = getConn().prepareStatement(sql);
    pstmt.execute();
    pstmt.close();
  }


  //关闭连接
  public void close() {
    try {
      getConn().close();

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}
